package com.atguigu.gmall.order.service.impl;


import com.atguigu.gmall.common.config.constant.MqCons;
import com.atguigu.gmall.common.config.service.RabbitService;
import com.atguigu.gmall.common.util.HttpClientUtil;
import com.atguigu.gmall.model.enums.OrderStatus;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.mapper.OrderDetailMapper;
import com.atguigu.gmall.order.mapper.OrderInfoMapper;
import com.atguigu.gmall.order.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${ware.url}")
    private String wareUrl;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RabbitService rabbitService;
    @Override
    public String tradeNo(String userId) {

        String key = "user:" + userId + ":tradeNo";
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set(key,tradeNo);
        return tradeNo;
    }

    @Override
    public Boolean checkTradeNo(String userId, String tradeNo) {
        String key = "user:" + userId + ":tradeNo";
        String no = (String) redisTemplate.opsForValue().get(key);
        if(!StringUtils.isEmpty(no)){
            if(no.equals(tradeNo)){
                return true;
            }
        }
        return false;
    }

    @Override
    public void deleteTradeNo(String userId) {
        String key = "user:" + userId + "tradeNo";
        redisTemplate.delete(key);
    }

    @Override
    public Long addOrder(OrderInfo orderInfo) {

        //订单状态
        orderInfo.setOrderStatus(OrderStatus.UNPAID.name());
        String outTradeNo = "ATGUIGU" + System.currentTimeMillis() + new Random().nextInt(1000);
        orderInfo.setOutTradeNo(outTradeNo);

        orderInfo.setCreateTime(new Date());

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,1);
        orderInfo.setExpireTime(calendar.getTime());

        orderInfo.setProcessStatus(ProcessStatus.UNPAID.name());

        StringBuilder tradeBody = new StringBuilder();

        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        orderDetailList.forEach(orderDetail -> {
            tradeBody.append(orderDetail.getSkuName() + " ");
        });
        if(tradeBody.length() > 100){
            tradeBody.subSequence(0,100);
        }
        orderInfo.setTradeBody(tradeBody.toString());

        orderInfo.sumTotalAmount();
        orderInfoMapper.insert(orderInfo);
        orderDetailList.forEach(orderDetail -> {
            orderDetail.setOrderId(orderInfo.getId());
            orderDetailMapper.insert(orderDetail);
        });
        //发消息
        System.out.println("发送延迟消息");
        rabbitService.sendDelayMessage(MqCons.EXCHANGE_DIRECT_ORDER_CANCEL,MqCons.ROUTING_ORDER_CANCEL,
                orderInfo.getId(),MqCons.DELAY_TIME);
        return orderInfo.getId();
    }

    @Override
    public Boolean checkStock(Long skuId, Integer skuNum) {
        String result = HttpClientUtil.doGet(wareUrl + "/hasStock?skuId=" + skuId + "&num=" + skuNum);
        return "1".equals(result);
    }

    //取消订单
    @Override
    public void cancelOrder(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        //订单未支付才可以取消  其它状态不可以自动取消
        if(null != orderInfo && OrderStatus.UNPAID.name().equals(orderInfo.getOrderStatus())){
            orderInfo.setId(orderId);
            //订单状态
            orderInfo.setOrderStatus(OrderStatus.CLOSED.name());
            //进度状态
            orderInfo.setProcessStatus(ProcessStatus.CLOSED.name());
            orderInfoMapper.updateById(orderInfo);
        }
    }

    @Override
    public OrderInfo getOrderInfo(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(new QueryWrapper<OrderDetail>().eq("order_id", orderId));
        orderInfo.setOrderDetailList(orderDetailList);
        orderInfo.sumTotalAmount();
        return orderInfo;
    }

    //更新订单状态
    @Override
    public void updateOrderStatus(OrderInfo orderInfo) {
        orderInfo.setOrderStatus(OrderStatus.PAID.name());
        orderInfoMapper.updateById(orderInfo);

    }
}
